package com.smart.config;


import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.smart.pojo.User;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.shiro.SecurityUtils;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDateTime;
import java.util.Date;

@Configuration
@MapperScan("com.smart.mapper")
public class MybatisPlusConfig {

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return mybatisPlusInterceptor;
    }

    @Bean
    public MetaObjectHandler metaObjectHandler() {
//        User subject = (User) SecurityUtils.getSubject().getPrincipal();
//        System.out.println("自动填充时认证主体：" + subject);
        return new MetaObjectHandler() {
            @Override
            public void insertFill(MetaObject metaObject) {
                this.setFieldValByName("createDate", LocalDateTime.now(), metaObject);
                this.setFieldValByName("createBy", SecurityUtils.getSubject().getPrincipal() == null ? null : ((User) SecurityUtils.getSubject().getPrincipal()).getId(), metaObject);
                this.setFieldValByName("updateDate", LocalDateTime.now(), metaObject);
                this.setFieldValByName("updateBy", SecurityUtils.getSubject().getPrincipal() == null ? null : ((User) SecurityUtils.getSubject().getPrincipal()).getId(), metaObject);
                this.setFieldValByName("delFlag", 0, metaObject);
            }

            @Override
            public void updateFill(MetaObject metaObject) {
                this.setFieldValByName("updateDate", LocalDateTime.now(), metaObject);
                this.setFieldValByName("updateBy", SecurityUtils.getSubject().getPrincipal() == null ? null : ((User) SecurityUtils.getSubject().getPrincipal()).getId(), metaObject);
//                this.setFieldValByName("updateBy", SecurityUtils.getSubject() == null ? null : 1L, metaObject);
            }
        };
    }
}
